package cn.kwq.project_manger.dtoUtils;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.kwq.project_manger.exception.UnBindWyuSystemException;
import cn.kwq.project_manger.pojo.*;
import cn.kwq.project_manger.pojo.dto.ResTeamDto;
import cn.kwq.project_manger.repostitory.*;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: kwq
 * @Date: 2023/02/23/13:46
 * @Description:
 */
@Data
@Component
@Slf4j
public class ResTeamDtoUtils {

    @Autowired
    JPAQueryFactory jpaQueryFactory;

    @Autowired
    TeamUserRepository teamUserRepository;

    @Autowired
    TagRepository tagRepository;

    @Autowired
    TeamTagRepository teamTagRepository;

    /**
     * 封装返回对象
     * @param save 原始对象
     * @return 返回对象
     */
    @NotNull
    public ResTeamDto Team2Res(Team save) {
        ResTeamDto res= new ResTeamDto();
        Optional.ofNullable(save).ifPresent(item->{
            res.Team(item);
            res.Tags(getTags(item.getTeamId()));
            res.Project(getProject(item.getTeamId()));
            QTeamUser tm=QTeamUser.teamUser;
            Long captionId = jpaQueryFactory.select(tm.UserId)
                    .from(tm)
                    .where(tm.isCaption.eq(1))
                    .where(tm.teamId.eq(item.getTeamId()))
                    .fetchOne();
            if (captionId != null) {
                res.setCaptionId(captionId);
            }else {
                log.error("没有队长错误：错误队伍["+item.getTeamId()+"]");
            }


            try {
                res.Member(getMembers(item.getTeamId(), item.getOriginators()));
            } catch (UnBindWyuSystemException e) {
                throw new RuntimeException(e);
            }
            try {
                res.MembersId(getMembers2(item.getTeamId(), item.getOriginators(),captionId));
            }catch (Exception e){
                log.error(e.getMessage());
            }
        });
        return res;
    }

    /**
     * 项目绑定标签
     * @param list 标签集合
     * @param teamId 队伍id
     */
    @Transactional
    public void bindTags(List<Long> list,Long teamId){
        log.info("执行项目绑定标签操作");
        //先删除原来已有标签
        QTeamTag pt=QTeamTag.teamTag;
        long execute = jpaQueryFactory.delete(pt)
                .where(pt.teamId.eq(teamId))
                .execute();

        for (Long tagId:list){
            if (execute!=0){
                log.info(teamId+"号队伍进行更新");
                log.info(teamId+"号队伍解除"+execute+"个标签绑定");
            }else {
                log.info(teamId+"号队伍，进行绑定标签");
            }
            teamTagRepository.save(
                    TeamTag.builder()
                            .tagId(tagId)
                            .teamId(teamId)
                            .build());

            log.info(teamId+"号队伍绑定标签成功");
        }
    }

    /**
     * 获取队伍成员
     * @param teamId 队伍id
     * @param captionName 队长名字
     * @return 成员得集合
     * @throws UnBindWyuSystemException 没绑定教务系统错误
     */
    @Transactional
    public List<String> getMembers(Long teamId, String captionName) throws UnBindWyuSystemException {
        QTeamUser teamUser=QTeamUser.teamUser;
        List<TeamUser> fetch = jpaQueryFactory.selectFrom(teamUser)
                .where(teamUser.teamId.eq(teamId))
                .fetch();
        List< String> members=new ArrayList<>();
        members.add("队长-"+captionName);

        for (TeamUser item : fetch) {
            if (item.getIsCaption().equals(0) || item.getIsCaption() == 0) {
                Long userId = item.getUserId();
                members.add("队员-" + getUserName(userId));
            }
        }

        return members;
    }

    /**
     *获取队伍成员带队员id版本
     * @param teamId 队伍id
     * @param captionName 队长名字
     * @return 成员得集合
     * @param captionId 队长id
     * @throws UnBindWyuSystemException 没绑定教务系统错误
     */
    @Transactional
    public List<String> getMembers2(Long teamId,String captionName,Long captionId) throws UnBindWyuSystemException {
        QTeamUser teamUser=QTeamUser.teamUser;
        List<TeamUser> fetch = jpaQueryFactory.selectFrom(teamUser)
                .where(teamUser.teamId.eq(teamId))
                .fetch();
        List< String> members=new ArrayList<>();
        members.add("队长-"+captionName+captionId);
        if (fetch!=null){
            for (TeamUser item : fetch) {
                if (item.getIsCaption().equals(0) || item.getIsCaption() == 0) {
                    Long userId = item.getUserId();
                    members.add("队员-" + getUserName(userId)+"-"+userId);
                }
            }
        }
        return members;
    }

    /**
     * 获取队伍参加得项目
     * @param teamId 队伍id
     * @return 项目对象集合
     */
    public List<Project> getProject(Long teamId){
        QProject project=QProject.project;
        QTeamProject teamProject=QTeamProject.teamProject;
        List<Project> fetch = jpaQueryFactory.selectFrom(project)
                .rightJoin(teamProject)
                .on(teamProject.projectId.eq(project.projectId))
                .where(teamProject.teamId.eq(teamId))
                .fetch();

        if (fetch!=null&&!fetch.isEmpty()&&fetch.get(0)==null){
            return null;
        } else {
            if (fetch!=null&&fetch.size()==0) {
                return null;
            }
        }
        return fetch;
    }

    /**
     * 获取用户名字
     * @param userId 用户id
     * @return 名字
     * @throws UnBindWyuSystemException 没绑定错误
     */
    public String getUserName(Long userId) throws UnBindWyuSystemException {
        QUser user=QUser.user;
        String s = jpaQueryFactory.select(user.userName)
                .from(user)
                .where(user.id.eq(userId))
                .fetchOne();
        if (s==null||s.isBlank()){
            throw new UnBindWyuSystemException("绑定教务系统才能创建队伍");
        }
        return s;

    }

    /**
     * 在成员表插入队长得信息
     * @param userId
     * @param teamId
     */
    @Transactional
    public void setCaption(Long userId,Long teamId) {
        teamUserRepository.save(TeamUser
                .builder()
                .isCaption(1)
                .teamId(teamId)
                .UserId(userId)
                .build());
    }

    /**
     * 获取队伍得标签集合
     * @param teamId
     * @return
     */
    @SaIgnore
    public List<String> getTags(Long teamId){
//        QTeam team=QTeam.team;
        QTag tag=QTag.tag;
        QTeamTag con=QTeamTag.teamTag;

        List<String> fetch = jpaQueryFactory
                .select(tag.tagName)
                .from(tag).leftJoin(con).on(con.tagId.eq(tag.tagId))
//                .leftJoin(team).on(con.tagId.eq(team.teamId))
                .where(con.teamId.eq(teamId))
                .fetch();

        System.out.println(fetch);
        if (fetch==null||fetch.isEmpty()||fetch.get(0)==null){
            return null;
        }
        return fetch;

    }
    /**
     * 标签名字集合转换为标签id集合（表里面没有的就新增）
     * @param tagName 标签名字
     * @return 队伍id
     */
    @Transactional
    public Long getTagIdByName(String tagName){
        QTag tag=QTag.tag;
        //查出tag表有当前标签
        Long tagID = jpaQueryFactory
                .select(tag.tagId)
                .from(tag)
                .where(tag.tagName.eq(tagName))
                .where(tag.tagType.eq(1))
                .fetchOne();
        log.info("标签 ["+tagName+"] 已存在，下面进行绑定");
        //没有就新增加这个标签
        if (tagID==null){
            log.info("标签 ["+tagName+"] 不存在，开始新增");

            Tag tagSave = tagRepository.save(Tag
                    .builder()
                    .tagType(1)
                    .tagName(tagName)
                    .build());

            String tagNameSave = tagSave.getTagName();
            log.info("新增 ["+tagNameSave+"] 标签成功");


            tagID = jpaQueryFactory
                    .select(tag.tagId)
                    .from(tag)
                    .where(tag.tagName.eq(tagName))
                    .where(tag.tagType.eq(1))
                    .fetchOne();
        }
        return  tagID;
    }


    /**
     * 标签名字集合转换为标签id集合（表里面没有的不新增）
     * @param tagNames 标签名字集合
     * @return 队伍id
     */
    @Transactional
    public List<Long> getTagIdButNotAdd(List<String> tagNames){
        List<Long> tagIdList=new LinkedList<>();
        tagNames.forEach(tagName->{
            QTag tag=QTag.tag;
            //查出tag表有当前标签
            Long tagID = jpaQueryFactory
                    .select(tag.tagId)
                    .from(tag)
                    .where(tag.tagName.eq(tagName))
                    .where(tag.tagType.eq(1))
                    .fetchOne();
            //没有就新增加这个标签
            if (tagID==null){
                throw new RuntimeException(tagName+" 标签不存在");
            }
            tagIdList.add(tagID);
        });
        if (!(tagIdList.size() >0)){
            return null;
        }
        return  tagIdList;
    }



}
